Verify Preorder Sequence in Binary Search Tree

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

Follow up:

Could you do it using only constant space complexity?

Solution:

  1. public class Solution {
  2. public boolean verifyPreorder(int[] preorder) {
  3. int low = Integer.MIN_VALUE;
  4. Stack<Integer> path = new Stack();
  5. for (int p : preorder) {
  6. if (p < low)
  7. return false;
  8. // If the current value is larger, we are going to the right
  9. // because of preorder, the numbers afterwards cannot be less
  10. // than the ones in the stack
  11. while (!path.empty() && p > path.peek())
  12. low = path.pop();
  13. path.push(p);
  14. }
  15. return true;
  16. }
  17. }